import Vue from 'vue'
import axios from 'axios'
import { Toast } from 'vant'
import utils from '../utils/util'
import router from "../router";

import _ from 'lodash';
let loadingInstance; //loading 实例
let needLoadingRequestCount = 0; //当前正在请求的数量

function showLoading() {
	let main = document.querySelector('body')
	if (main) {
		if (needLoadingRequestCount === 0 && !loadingInstance) {
			loadingInstance = Toast.loading({
				message: '加载中...',
				forbidClick: true,
			});
		}
		needLoadingRequestCount++;
	}
}
function closeLoading() {
	Vue.nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
		needLoadingRequestCount--;
		needLoadingRequestCount = Math.max(needLoadingRequestCount, 0); // 保证大于等于0
		if (needLoadingRequestCount === 0) {
			if (loadingInstance) {
				hideLoading()
			}
		}
	});
}

var hideLoading = _.debounce(() => {
	loadingInstance.close();
	loadingInstance = null;
}, 300);


axios.interceptors.request.use(config => { // request拦截器
	showLoading()
	return config
}, err => {
	// closeLoading()
	return Promise.reject(err);
})

axios.interceptors.request.use(
	request => {
		request.headers['token'] = utils.SessionGet('token') ? utils.SessionGet('token') : ''
		request.headers['version'] = "v3.5"
		request.headers['from'] = "app"
		request.headers['opr'] = "1024"
		return request
	}
)

axios.interceptors.response.use(
	response => {
		if (response.data.code == '0') {
			closeLoading()
			return response.data
		}else {
			closeLoading()
			Toast.fail(response.data.msg)
			return response.data
		}
		
	}, error => {
		console.log(error.response);
		if(error.response.status == 401 || utils.SessionGet('token') == '') {
			Toast("登录已经过期，请重新登录!")
			utils.SessionRemove('token')
			router.push({ path: "/index", query: { token : ''} });
			return
		}
		closeLoading()
		return Promise.reject(error)
	}
)

export default axios